package com.wodsy.phoenix.dataservice.base.advice;

import com.wodsy.phoenix.dataobject.base.PhoenixRequest;
import com.wodsy.phoenix.dataobject.base.PhoenixResponseWrapper;
import com.wodsy.phoenix.dataobject.base.ResponseCodeConstants;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * 统一的参数检查advice
 * 名称：com.wodsy.orderc.dataservice.service.impl
 * 描述：<br>
 * 类型：JAVA<br>
 * 最近修改时间：09/03/2015 15:57<br>
 *
 * @author Jack Chan
 * @since 09/03/2015
 */
public class ServiceAdvice {
    private Logger logger = Logger.getLogger(ServiceAdvice.class);
    private final static Validator validator= Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 参数检查aspect
     * @param joinPoint
     */
    public Object paramCheck(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if(ArrayUtils.isNotEmpty(args)) {
            for (Object arg : args) {
                if(arg instanceof PhoenixRequest) {
                    Set<ConstraintViolation<Object>> validate = validator.validate(arg);
                    //如果存在异常
                    if(CollectionUtils.isNotEmpty(validate)) {
                        for (ConstraintViolation<Object> constraintViolation : validate) {
                            String errorMsg = "param error : " + constraintViolation.getPropertyPath() + " : " + constraintViolation.getMessage();
                            logger.error(errorMsg, new IllegalArgumentException());
                            return new PhoenixResponseWrapper(ResponseCodeConstants.REQUEST_PARAM_ERROR, "request params error");
                        }
                    }
                }
            }
        }

        return joinPoint.proceed();
    }


    /**
     * 如果发生异常，返回给调用端异常信息
     * @return
     */
    public Object exceptionResult(JoinPoint joinPoint,
                                  RuntimeException  throwable) {
        String msg = "method: " + joinPoint.getSignature().getName() + " invoke exception: " + throwable.fillInStackTrace();
        return new PhoenixResponseWrapper(ResponseCodeConstants.EXCEPTION, msg);
    }
}
